<?php
declare(strict_types=1);
namespace app\admin\controller;
use aphp\core\Jump;
use extend\upload\Upload;

class Api
{
	use Jump;
    protected string $middleware = 'rbac';

    public function clear()
    {
        cache_clear();
        cli('clear:runtime admin index common');
        $this->success('清除缓存成功', 'index/index');
    }

    // 文件上传接口
    public function upload(string $api = 'image')
    {
        $upload = Upload::init($api);
        $res = $upload->save();
        if (!isset($res[0]['path'])) {
            $this->error($upload->getError());
        }
        $res[0]['attach_id'] = $this->_attach_to_database($res[0]); // 存入附件表
        $this->_json(200, '上传成功', $res[0]);
    }

    // 存入附件表
    protected function _attach_to_database(array $file)
    {
        $data = [];
        $data['type'] = $file['file_type'];
        $data['title'] = $file['name'];
        $data['path'] = $file['path'];
        $data['size'] = $file['size'];
        $data['mime'] = $file['type'];
        $data['ext'] = $file['ext'];
        $data['upload_api'] = $file['api_type'];
        $data['admin_id'] = session('user.id');
        $data['upload_time'] = $file['upload_time'];
        $data['status'] = 1;
        return db('attach')->insertGetId($data);
    }

    // 头像上传
    public function base64_upload()
    {
        $api = input('post.api', 'image', 'clear_html'); // 上传类型
        $data = input('post.base64'); // base64数据
        $uid = session('user.id'); // 用户id
        $upload = Upload::init($api);
        $res = $upload->saveBase64Image($data, 'uid_'.$uid);
        if (!isset($res['path'])) {
            $this->error($upload->getError());
        }
        if ($res['api_type'] == 'avatar') {
            db('admin')->where('id', $uid)->setField('avatar', $res['path']);
        }
        $this->_json(200, '上传成功', ['path' => $res['path']]);
    }
}